clear all
cls

local path_rawdata 	= "00_data/00_raw_data"
local path_inputs 	= "00_data/01_datasets/00_inputs"
local path_FTapp 	= "03_figures_tables/02_Appendix"


local Figure_B1 			= 1
local Table_and_Figure_B2 	= 1
local Figure_B3 			= 1
local Figure_B4_to_B6 		= 1


if `Figure_B1'==1 {

/// ------------------------------------------------------------------------------------------------ ///
/// ---------------------------------------------  GDP: Arg vs LATAM-------------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///    
import excel "`path_rawdata'/01_LAC_GDP.xlsx", sheet("ID_CODE") firstrow
drop code
rename ID ctyID
save "temp.dta", replace
clear

import excel "`path_rawdata'/01_LAC_GDP.xlsx", sheet("GDP") firstrow
reshape long cty, i(date) j(ctyID)
rename cty GDP_index

qui gen ln_GDP = ln(GDP_index)
sort ctyID date
bysort ctyID: gen time = _n

merge m:1 ctyID using "temp.dta"
drop _merge
erase "temp.dta"

sort ctyID date

xtset ctyID date

qui gen GDP_growth = .

qui sum ctyID
local Ncty = r(max)

forval ii=1(1)`Ncty' {
    qui sum ln_GDP if ctyID==`ii'
    local Nobs = r(N)
    if `Nobs'>0{
        qui replace GDP_growth = (GDP_index/GDP_index[_n-4]-1)*100
    }
}

qui sum GDP_growth if ( date>=d(1jun2005) & date<=d(1dec2012) & (country=="Argentina"|country=="Brazil"|country=="Chile"|country=="Colombia"|country=="Mexico"|country=="Peru"|country=="Uruguay"))
local min_growth = r(min)
qui gen area_GR = r(max)
label variable area_GR "GR"

gen GFC=0
replace GFC=1 if date>=d(1mar2008) & date<=d(30dec2009)
keep if date>=d(1jun2005) & date<=d(1dec2012)
graph twoway ( area area_GR date if GFC==1, color(gs13)  base(`min_growth') ) /*
*/ ( line GDP_growth date if country=="Argentina", lcolor(black) lwidth(0.4) plotregion(color(white)) graphregion(color(white)) bgcolor(white) /*
*/  tlabel(01jan2005 01jan2006 01jan2007  01jan2008 01jan2009  01jan2010 01jan2011 01jan2012 01jan2013, format(%tdCY))  ytitle("%")  ) /*
*/ ( line GDP_growth date if country=="Brazil"   , lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line GDP_growth date if country=="Chile" ,    lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line GDP_growth date if country=="Colombia" , lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line GDP_growth date if country=="Mexico" ,   lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line GDP_growth date if country=="Peru" ,     lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line GDP_growth date if country=="Uruguay" ,  lcolor(gray)  lwidth(0.15) lpattern(dash)  ylabel(-6(4)12) leg(off)  xtitle("") )
graph export "`path_FTapp'/LATAM_RealGDPgrowth.pdf", replace
drop area_GR



/// ------------------------------------------------------------------------------------------------ ///
/// ------------------------------------    STOCK MARKET:Arg vs LATAM     -------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///
clear
import excel "`path_rawdata'/00_StockIndex_LAC.xls", sheet("monthly") cellrange(A2:G228) firstrow

qui gen mdate = mofd(Date)
format mdate %tm

order mdate

tsset mdate

qui gen dAR = (AR/L12.AR)-1
qui gen dBR = (BR/L12.BR)-1
qui gen dCL = (CL/L12.CL)-1
qui gen dCO = (CO/L12.CO)-1
qui gen dMX = (MX/L12.MX)-1
qui gen dPE = (PE/L12.PE)-1

label variable dAR "Argentina"
label variable dBR "Brazil"
label variable dCL "Chile"
label variable dCO "Colombia"
label variable dMX "Mexico"
label variable dPE "Peru"

qui gen area_GR = 2.5
label variable area_GR "GR"

gen GFC=0
replace GFC=1 if mdate>=mofd(d(1mar2008)) & mdate<=mofd(d(30dec2009))
keep if mdate>=mofd(d(1jun2005)) & mdate<=mofd(d(1dec2012))

graph twoway ( area area_GR mdate if GFC==1, color(gs13) base(-1)  ) /*
*/ ( line dAR mdate , lcolor(black) lwidth(0.4) plotregion(color(white)) graphregion(color(white)) bgcolor(white) /*
*/   tlabel(2005m1 2006m1 2007m1 2008m1 2009m1 2010m1 2011m1 2012m1 2013m1, format(%tmCY))  ytitle("%")  ) /*
*/ ( line dBR mdate  , lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line dCL mdate ,    lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line dCO mdate , lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line dMX mdate ,   lcolor(gray)  lwidth(0.15) lpattern(dash) ) /*
*/ ( line dPE mdate ,  lcolor(gray)  lwidth(0.15) lpattern(dash)  ylabel(-1(0.5)2.5)  leg(off)  xtitle("") )
graph export "`path_FTapp'/stocks_growth.pdf", replace	

drop area_GR
clear

}
// ------------------------------------------------------------------------------------------------------- //
// ------------------------------------------------------------------------------------------------------- //
// END OF `Figure_B1'==1





if `Table_and_Figure_B2'==1 {

/// ------------------------------------------------------------------------------------------------ ///
/// ------------------------------------  ARGENTINE BOND YIELDS  ----------------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///

local US_main_1       = 84
local US_main_2       = 36
local Pesos_bond_id   = 102
local IIB_bond_id     = 9

use "`path_inputs'/01_Arg_Bonds_Data.dta", clear
qui drop if Date<d(01jan2006)
qui drop if Date>=d(01jan2012)
qui  keep if Curr == "ARS" | Curr == "USD"

* Change to missing Yields after bond mature
*-------------------------------------------------------
qui replace Ask_Annual_Yield=. if Date[_n]>Maturity[_n]


*-------------------------------------------------------------------------------
* IIBS
*-------------------------------------------------------------------------------
preserve
	keep if InflationLinkedNote=="Y"
	*Drop outliers (yields>100)
		drop if Bond_ID==20 | Bond_ID==8 | Bond_ID==21 // outliers
	*Drop bonds with no data
		drop if Bond_ID==2  | Bond_ID==3  | Bond_ID== 5 | Bond_ID==6   | Bond_ID==7  | Bond_ID==11 | ///
				Bond_ID==11 | Bond_ID==12 | Bond_ID==13 | Bond_ID== 14 | Bond_ID==15 | Bond_ID==16 | ///
				Bond_ID==18 | Bond_ID==19 | Bond_ID==22
	*Drop one more outlier (bond with little variation in yield)
		drop if Bond_ID ==1

	*Graph (sort first IIB used in the baseline analysis)
	replace ISIN = " "+ISIN if Bond_ID==`IIB_bond_id'   //IIB used in main analysis
	encode ISIN, gen(ISIN_tmp)
	xtset ISIN_tmp Date

	xtline  Ask_Annual_Yield , overlay /// 
			plot1(lc(blue)   lwidt(medium)) ///  *IIB used in main analysis
			plot2(lc(black) lwidt(vthin)) /// 
			plot3(lc(black) lwidt(vthin)) /// 
			plot4(lc(black) lwidt(vthin)) /// 
			ytitle("Bond Yields", size(small)) ylabel(, nogrid labsize(small)) tlabel(, nogrid labsize(small)) xtitle("Date",  size(small)) ///
	        legend(off) graphregion(color(white)) plotregion(color(white))  tlabel(, format(%dm-CY)) saving(aa0.gph, replace) 


	xtline  Ask_Annual_Yield if Date<=d(01mar2008), overlay /// 
			plot1(lc(blue)   lwidt(medium)) ///  *IIB used in main analysis
			plot2(lc(black) lwidt(vthin)) /// 
			plot3(lc(black) lwidt(vthin)) /// 
			plot4(lc(black) lwidt(vthin)) /// 
			ytitle("Bond Yields", size(small)) ylabel(, nogrid labsize(small)) tlabel(, nogrid labsize(small)) xtitle("Date",  size(small)) ///
	        legend(off) graphregion(color(white)) plotregion(color(white))  tlabel(, format(%dm-CY)) saving(aa1.gph, replace) 

	*Combine and save
	gr combine aa0.gph aa1.gph, ysize(3) col(2) graphregion(color(white)) plotregion(color(white))
		qui graph export "`path_FTapp'/YieldsIIBs_graph.pdf", replace

		erase "aa0.gph"
		erase "aa1.gph"

	*Store static information
	duplicates drop ISIN, force		
	keep ISIN InflationLinkedNote Maturity MaturityType Curr Cpn  CpnFreqDes Bond_ID

	*Create and export .tex table
		sort Maturity
		generate Maturity_string = string(Maturity, "%td")
		replace ISIN = ISIN+"(*)" if Bond_ID==`IIB_bond_id'
		tempname table_SummaryStats
		file open table_SummaryStats using "`path_FTapp'/IIBs_static.tex", write replace
		file write table_SummaryStats "\renewcommand{\arraystretch}{1.5}"
		file write table_SummaryStats "\begin{tabular}{lcccc}" _n "\hline \hline" _n
		file write table_SummaryStats "\quad ISIN & Maturity  & Currency & Coupon Frequency\\" _n
		file write table_SummaryStats "\cline{1-3}" _n
		file write table_SummaryStats "\hline \hline" _n
		forval i=1/4{
		file write table_SummaryStats (ISIN[`i']) "&" (Maturity_string[`i']) "&" (Curr[`i'])  "&" (CpnFreqDes[`i']) " \\" _n
		}
		file write table_SummaryStats "\hline \hline" _n
		file write table_SummaryStats "\end{tabular}" _n
		file close table_SummaryStats

restore



*------------------------------------------------------------------------------------------------
* BONDS IN DOLLARS
*------------------------------------------------------------------------------------------------

preserve
	keep if InflationLinkedNote=="N" & (Curr=="USD" | Curr=="ARS")
	    
	* CLEANING FOR BONDS IN DOLLARS
		keep if Curr=="ARS" | Bond_ID==28 |Bond_ID== 30 |Bond_ID==33 |Bond_ID==36 | Bond_ID==82 | Bond_ID==84 
	* CLEANING FOR BONDS IN PESOS
		*There is only 1 bond with data: Bond_ID==102
		drop if (Curr=="ARS" & Bond_ID!=102)

	*Graph (sort first bonds to have bond in pesos and the one used in dollars first)
	gen ISIN_Curr = ISIN+"("+Curr+")"
	replace ISIN_Curr = " " +ISIN_Curr   if Bond_ID==`US_main_1' | Bond_ID==`US_main_2'   // Bond in dollars used in main analysis
	replace ISIN_Curr   = "  "+ISIN_Curr if Bond_ID==`Pesos_bond_id'        // Bond in pesos
	encode ISIN_Curr, gen(ISIN_tmp)
	xtset ISIN_tmp Date	

	*SAME PLOT WITH ONLY BOND IN DOLLARS
	gen   ISIN_plot     = ISIN_Curr
	replace ISIN_plot   = " "+ISIN_Curr if Bond_ID==`US_main_1' | Bond_ID==`US_main_2' 
	encode ISIN_plot, gen(ISIN_tmp_2)
	xtset ISIN_tmp_2 Date

	*Including the crisis period
	xtline  Ask_Annual_Yield if Bond_ID!=`Pesos_bond_id', overlay  ///
			plot1(lc(blue)  lwidt(medium)) ///  *Bond in dollars used in main analysis
			plot2(lc(blue)  lwidt(medium)) ///  *Bond in dollars used in main analysis
			plot3(lc(black) lwidt(vthin)) ///
			plot4(lc(black) lwidt(vthin)) ///
			plot5(lc(black) lwidt(vthin)) ///
			plot6(lc(black) lwidt(vthin)) ///
	        ytitle("Bond Yields", size(small)) ylabel(, nogrid labsize(small)) tlabel(, nogrid labsize(small)) xtitle("Date",  size(small)) ///
	        legend(off) graphregion(color(white)) plotregion(color(white))  tlabel(, format(%dm-CY)) saving(aa2.gph, replace) 

	*Before the crisis period
	xtline  Ask_Annual_Yield if Bond_ID!=`Pesos_bond_id' & Date<=d(01mar2008), overlay  ///
			plot1(lc(blue)  lwidt(medium)) ///  *Bond in dollars used in main analysis
			plot2(lc(blue)  lwidt(medium)) ///  *Bond in dollars used in main analysis
			plot3(lc(black) lwidt(vthin)) ///
			plot4(lc(black) lwidt(vthin)) ///
			plot5(lc(black) lwidt(vthin)) ///
			plot6(lc(black) lwidt(vthin)) ///
	        ytitle("Bond Yields", size(small)) ylabel(, nogrid labsize(small)) tlabel(, nogrid labsize(small)) xtitle("Date",  size(small)) ///
	        legend(off) graphregion(color(white)) plotregion(color(white))  tlabel(, format(%dm-CY)) saving(aa3.gph, replace) 
	*Combine and save
	gr combine aa2.gph aa3.gph, ysize(3) col(2) graphregion(color(white)) plotregion(color(white))
	qui graph export "`path_FTapp'/Yields_Dollars_Bonds_graph.pdf", replace

	erase "aa2.gph"
	erase "aa3.gph"

	*Store static information
	duplicates drop ISIN_Curr, force		
	keep ISIN ISIN_Curr InflationLinkedNote Maturity MaturityType Curr Cpn  CpnFreqDes Bond_ID

	*Create and export .tex table
		sort Curr Maturity
		generate Maturity_string = string(Maturity, "%td")
		replace ISIN = ISIN+"(*)" if Bond_ID==`US_main_1' | Bond_ID==`US_main_2' 
		tempname table_SummaryStats
		file open table_SummaryStats using "`path_FTapp'/Dollar_Pesos_static.tex", write replace
		file write table_SummaryStats "\renewcommand{\arraystretch}{1.5}"
		file write table_SummaryStats "\begin{tabular}{lcccc}" _n "\hline \hline" _n
		file write table_SummaryStats "\quad ISIN & Maturity  & Currency & Coupon Frequency\\" _n
		file write table_SummaryStats "\cline{1-3}" _n
		file write table_SummaryStats "\hline \hline" _n
		forval i=1/7{
		file write table_SummaryStats (ISIN[`i']) "&" (Maturity_string[`i']) "&" (Curr[`i'])  "&" (CpnFreqDes[`i']) " \\" _n
		}
		file write table_SummaryStats "\hline \hline" _n
		file write table_SummaryStats "\end{tabular}" _n
		file close table_SummaryStats	

restore

}

// ------------------------------------------------------------------------------------------------------- //
// ------------------------------------------------------------------------------------------------------- //
// END OF `Table_Fig_B2'==1




if `Figure_B3'==1 {
/// ------------------------------------------------------------------------------------------------ ///
/// ------------------------------  MEASURES OF BREAK-EVEN INFLATION  ------------------------------ ///
/// ------------------------------------------------------------------------------------------------ ///

use  "`path_inputs'/03_BreakEvenInflation.dta", clear

tset Date
			
keep if  Date>=d(01oct2006) & Date<=d(01mar2008)
drop if Date>=d(16aug2007) & Date<=d(17aug2007)
	*Before the crisis period
	 twoway (line BE_1 Date , lc(black) lwidt(vthin)) ///
			(line BE_2 Date , lc(black) lwidt(vthin)) ///
			(line BE_3 Date , lc(black) lwidt(vthin)) ///
			(line BE_4 Date , lc(black) lwidt(vthin)) ///
			(line BE   Date , lc(blue) lwidt(medium)   ///
	        ytitle("BE", size(small)) ylabel(, nogrid labsize(small)) tlabel(, nogrid labsize(small)) xtitle("Date",  size(small)) ///
	        legend(off) graphregion(color(white)) plotregion(color(white))  tlabel(, format(%dm-CY)) saving(aa0.gph, replace))
	 qui graph export "`path_FTapp'/BE_DollarBonds_graph.pdf", replace

erase "aa0.gph"

clear

}
// ------------------------------------------------------------------------------------------------------- //
// ------------------------------------------------------------------------------------------------------- //
// END OF `Figure_B3'==1




if `Figure_B4_to_B6' == 1{

/// ------------------------------------------------------------------------------------------------ ///
/// ------------- Changes in Break-even Inflation, yields differentials, and misreport  ------------ ///
/// ------------------------------------------------------------------------------------------------ ///
use "`path_inputs'/01_Arg_Inflation.dta",clear
tset Date_Month
drop if Date==.
merge 1:1 Date using "`path_inputs'/03_BreakEvenInflation.dta" , keepusing(BE Yield_diff devaluation_avg)
sort Date
gen date_id =_n
tset date_id

global window_type  = -1  // 2-day window

do "01_codes/00_CreateWindows_fx.do"

forval i=1/4{
preserve
	* DELTA CHANGE IN THE BE
    if `i'==1 {
	gen BE_Change =  (BE-L.BE) // abs change
	local text_cord_1  = 0.1
	local text_cord_2  = 1.2
	local text_cord_3  = `text_cord_1'-0.03
	}
	if `i'==2 {
	gen BE_Change =  (BE-L.BE) // abs change
	local text_cord_1  = 0.01
	local text_cord_2  = -0.95
	local text_cord_3  = `text_cord_1'-0.10
	}
	
	* YIELD DIFFERENCE (without the NXR change)
	if `i'==3  {
	gen BE_Change = Yield_diff - L.Yield_diff
	local text_cord_1  =  0.05
	local text_cord_2  =  1.0
	local text_cord_3  = `text_cord_1'-0.03
	}
	if `i'==4{
	gen BE_Change = Yield_diff - L.Yield_diff
	local text_cord_1  = -0.05
	local text_cord_2  = -0.90
	local text_cord_3  = `text_cord_1'-0.1
	}
	
	if `i'==1 | `i'==3 {
	keep if Date<=d(01mar2008) & Date>=d(01jan2007)
	}
	if `i'==2 | `i'==4 {
	keep if  (Date>=d(01mar2008)  & Date<=d(01mar2011))
	}

	collapse (mean) BE BE_Change Inf_Misreport_Change Date, by(EVENT_ID)
	reg BE_Change Inf_Misreport_Change, robust
     
	 local b =  _b[Inf_Misreport_Change]
 
	 qui matrix aa1    =  e(V) 
	 qui scalar se_tmp = sqrt(aa1[1,1])
	 local p           = (2 * ttail(e(N)-2, abs(_b[Inf_Misreport_Change]/se_tmp))) //two-sided p-val

 	 local b : display %04.3f `b'
 	 local p : display %04.3f `p'

	sum BE_Change if Inf_Misreport_Change<0
	sum BE_Change if Inf_Misreport_Change>0
	generate pos=9
	replace pos=6 if Inf_Misreport_Change<-0.25

	gen Date_m = mofd(Date)
	format Date_m %tm
	if `i'==1 | `i'==2 { 
	local ylabel_text = "Change in BE rate (in pp)"
	}
	if `i'==3 | `i'==4 { 
	local ylabel_text = "Change in yield differentials (in pp)"
	}
	twoway (scatter BE_Change Inf_Misreport_Change,    mlabsize(small) mlabv(pos) xtitle("Change in misreport (monthly rate, in pp)", size(small)) ytitle("`ylabel_text'",  size(small)) xlabel(, labsize(small)) ylabel(, nogrid labsize(small)) plotregion(color(white)) graphregion(color(white)))  ///
		   (lfit BE_Change Inf_Misreport_Change, lwidth(medthick) lpattern(dash) lcolor(black) leg(off) text(`text_cord_1' `text_cord_2' "beta=`b'", place(e) size(small))  text(`text_cord_3' `text_cord_2' "p-val=`p'", place(e) size(small)))
	
	if `i'==1 {
	qui graph export "`path_FTapp'/Scatter_BE_Misreport_Scatter_pre.pdf", replace
	}
	if `i'==2{
	qui graph export "`path_FTapp'/Scatter_BE_Misreport_Scatter_post.pdf", replace
	}
	if `i'==3 {
	qui graph export "`path_FTapp'/Scatter_Yield_Misreport_Scatter_pre.pdf", replace
	}
	if  `i'==4 {
	qui graph export "`path_FTapp'/Scatter_Yield_Misreport_Scatter_post.pdf", replace
	}
restore

}


/// ------------------------------------------------------------------------------------------------ ///
/// ---------------- Changes in Expected Depreciation Rate and Inflation Misreport ----------------- ///
/// ------------------------------------------------------------------------------------------------ ///

use "`path_inputs'/01_Arg_Inflation.dta",clear
tset Date_Month
drop if Date==.
merge 1:1 Date using "`path_inputs'/03_BreakEvenInflation.dta" , keepusing(BE  devaluation devaluation_avg)
sort Date
gen date_id =_n
tset date_id

global window_type  = -1  // 2-day window
do "01_codes/00_CreateWindows_fx.do"

matrix Dev_Change_table = J(6,2,.)
forval i=1/2{

preserve

	* Averaged [5-day rolling window]
    if `i'==1{
	gen Dev_Change_pre   =  devaluation_avg-L.devaluation_avg  if   Date<=d(01mar2008) & Date>=d(01jan2007)
	gen Dev_Change_post  =  devaluation_avg-L.devaluation_avg  if  (Date>=d(01mar2008)  & Date<=d(01mar2011))
	local text_cord_1  = -0.1
	local text_cord_2  = 1.0
	local text_cord_3  = `text_cord_1'-0.05
	}
	
	* Not averaged
	if `i'==2  {
	gen Dev_Change_pre   =  devaluation-L.devaluation  if   Date<=d(01mar2008)  & Date>=d(01jan2007)
	gen Dev_Change_post  =  devaluation-L.devaluation  if  (Date>=d(01mar2008)  & Date<=d(01mar2011))
	local text_cord_1  = -0.2
	local text_cord_2  = 1.0
	local text_cord_3  = `text_cord_1'-0.1
	}
	
	collapse (median) BE Dev_Change_pre Dev_Change_post Inf_Misreport_Change Date, by(EVENT_ID)
	
	sum Dev_Change_post ,detail
	drop if Dev_Change_post  <= -0.7   // only 1 outlier out
	
	* Fit linear trend only for the pre 2008 sample
	reg Dev_Change_pre Inf_Misreport_Change, robust
    local b =  _b[Inf_Misreport_Change]

	qui matrix aa1 =  e(V) 
	qui scalar se_tmp = sqrt(aa1[1,1])
	local p  = (2 * ttail(e(N)-2, abs(_b[Inf_Misreport_Change]/se_tmp))) //two-sided p-val


	local b : display %04.3f `b'
 	local p : display %04.3f `p'
	 
	generate pos=9
	replace pos=6 if Inf_Misreport_Change<-0.25

	gen Date_m = mofd(Date)
	format Date_m %tm
	twoway (scatter Dev_Change_pre Inf_Misreport_Change  if abs(Dev_Change_pre)<1,    mlabsize(small) mlabv(pos) xtitle("Change in misreport (monthly rate, in pp)", size(small)) ytitle("Change in expected depreciation (12-month, in pp)",  size(small)) xlabel(, labsize(small)) ylabel(, nogrid labsize(small)) plotregion(color(white)) graphregion(color(white)))  ///
	       (scatter Dev_Change_post Inf_Misreport_Change if abs(Dev_Change_post)<1,   mlabsize(small) mlabv(pos) xtitle("Change in misreport (monthly rate, in pp)", size(small)) ytitle("Change in expected depreciation (12-month, in pp)",  size(small)) xlabel(, labsize(small)) ylabel(, nogrid labsize(small)) plotregion(color(white)) graphregion(color(white)))  ///
		   (lfit Dev_Change_pre Inf_Misreport_Change, lwidth(medthick) lpattern(dash) lcolor(black) leg(off) text(`text_cord_1' `text_cord_2' "beta=`b'", place(e) size(small))  text(`text_cord_3' `text_cord_2' "p-val=`p'", place(e) size(small)))
	if `i'==1{
	qui graph export "`path_FTapp'/Scatter_Devaluation_Misreport_Scatter_average.pdf", replace
	}
	if `i'==2{
	qui graph export "`path_FTapp'/Scatter_Devaluation_Misreport_Scatter_no_average.pdf", replace
	}
restore
}




/// ------------------------------------------------------------------------------------------------ ///
/// ----------------- DEPRECIATION FROM BCRA EXPECTATIONS SURVEY AND DEPOSIT RATES ----------------- ///
/// ------------------------------------------------------------------------------------------------ ///

// -------------------------------------------------------------------------------------------------
// DEPRECIATION FROM BCRA EXPECTATIONS SURVEY AND DEPOSIT RATES

*** Inflation Misreport
import excel "`path_rawdata'/00_Arg_Inflation_Announcements.xls", sheet("DATA") cellrange(A2:H122) firstrow clear
format AnnouncementDate %d
rename AnnouncementDate IndecDate
qui egen Inf_Private_AVG = rowmean(IPC_FIEL PriceStats IPC7 IPC_BAC IPC_Congreso)
qui gen Inf_Misreport    = IPC_INDEC    - Inf_Private_AVG
keep IndecDate Inf_Misreport
drop if IndecDate==.
sort IndecDate
qui gen time = _n
tsset time
qui gen dMisrep = Inf_Misreport-L1.Inf_Misreport
qui gen week = week(IndecDate)
qui gen month_indec = month(IndecDate)
qui gen year = year(IndecDate)
sort IndecDate
drop time
save "`path_inputs'/temp_inflation.dta", replace
clear


*** IMPORT DATA ON EXPECTATIONS ON NXR
import excel "`path_rawdata'/02_Arg_NXR_Expectations.xlsx", sheet("ALL") firstrow clear
qui gen week = week(ExpDate)
qui gen year = year(ExpDate)
keep if year>=2006 & year<=2012

// MERGE WITH DATASET ON MISREPORT
sort ExpDate
merge m:1 year week using "`path_inputs'/temp_inflation.dta"
drop if _merge==2
drop _merge


// MERGE WITH DATASET ON NXR
sort ExpDate
merge m:1 year week using "`path_inputs'/01_NXR_weekly.dta"
drop if _merge==2
drop _merge


keep if (Period=="2006-ANL" | Period=="2007-ANL" | Period=="2008-ANL" | Period=="2009-ANL" | Period=="2010-ANL" | Period=="2011-ANL" | Period=="2012-ANL" )

* Generate time variable
preserve
	collapse (mean) Avg, by(ExpDate)
	sort ExpDate
	qui gen time = _n
	drop Avg
	save "`path_inputs'/tmp_time.dta", replace
restore

sort ExpDate Period
merge m:1 ExpDate using "`path_inputs'/tmp_time.dta"
drop _merge
erase "`path_inputs'/tmp_time.dta"

bysort ExpDate: gen ID=_n
order ID

sort ID time
xtset ID time


// COMPUTE EXPECTED DEPRECIATION TO DECEMBER
qui gen OffDep    = (Avg/TC_Officialm1-1)*100
drop if year<=2006 | year>=2012

// Cases with current and next year expectation
bysort ExpDate: gen NN = _N
order NN
sort ExpDate Period

// INDEX FOR CURRENT AND FOLLOWING YEAR
sort ExpDate Period
qui gen indM = 0
qui replace indM = 1 if ExpDate==ExpDate[_n-1]

order indM


// COMPUTE EXPECTED 12-MONTH DEPRECIATION
qui gen mdate = ym(year(ExpDate), month(ExpDate))
format mdate %tm
qui gen month_rep = month(dofm(mdate))

sort ExpDate Period

qui gen NXR12Mdep = (12-month_rep)/12*OffDep + month_rep/12*OffDep[_n+1] if indM==0 & NN==2
qui replace NXR12Mdep = ( (1+OffDep/100)^((12+month_rep)/12)-1 )*100 if indM==0 & NN==1

keep if indM==0

sort ExpDate
qui gen d12Mdep    = NXR12Mdep-NXR12Mdep[_n-1]


* Scatter with sample separation pre/post 08
	qui reg d12Mdep dMisrep if ExpDate<=d(01mar2008), robust
	qui local beta = round(_b[dMisrep],.001)

	qui matrix var_tmp = e(V)
 	qui local se_tmp   = sqrt(var_tmp[1,1])
    qui local pval     = (2 * ttail(e(N)-2, abs(`beta'/`se_tmp'))) //two-sided p-val

	 local beta : display %04.3f `beta'
 	 local pval : display %04.3f `pval'
	

twoway (scatter d12Mdep dMisrep if ExpDate<=d(01mar2008), graphregion(color(white)) plotregion(color(white)) bgcolor(white) ytitle("Change in expected depreciation (12-month, in pp)", size(small))) /*
*/ (scatter d12Mdep dMisrep if ExpDate>d(01mar2008), msize(small) xtitle("Change in misreport (monthly rate, in pp)", size(small)) ) /*
*/ (lfit d12Mdep dMisrep if ExpDate<=d(01mar2008), text(1.4 1.0 "beta=`beta'", place(e) size(small))  text(1. 1.0 "p-val=`pval'", place(e) size(small))  color(black) legend(off) lpattern(dash) )
qui graph export "`path_FTapp'/Scatter_Dmisrep_Ddeprec12m_v3.pdf", replace
// -------------------------------------------------------------------------------------------------


// -------------------------------------------------------------------------------------------------
// DEPRECIATION FROM TIME DEPOSIT RATES

import excel "`path_rawdata'/02_Arg_Deposit_Rates.xlsx", sheet("Rates") firstrow clear

qui gen year = year(Date)
qui gen month_indec = month(Date)
sort Date
merge 1:1 year month_indec using "`path_inputs'/temp_inflation.dta"
keep if _merge==3
drop _merge
erase "`path_inputs'/temp_inflation.dta"

sort Date
qui gen time = _n
tsset time
qui gen difNM  = Domestic-Foreign
qui gen DdifNM = difNM-L1.difNM

keep if year>=2007 & year<=2011

* Scatter DdifNM dMisrep
	qui reg DdifNM dMisrep if Date<=d(01mar2008), robust
	qui local beta = _b[dMisrep]

	qui matrix var_tmp = e(V)
 	qui local se_tmp   = sqrt(var_tmp[1,1])
    qui local pval     = (2 * ttail(e(N)-2, abs(`beta'/`se_tmp'))) //two-sided p-val

	local beta : display %04.3f `beta'
 	local pval : display %04.3f `pval'
	 

twoway (scatter DdifNM dMisrep if Date<=d(01mar2008), graphregion(color(white)) plotregion(color(white)) bgcolor(white) ytitle("Change in R(LC)-R(FC) (in pp)", size(small))) /*
*/ (scatter DdifNM dMisrep if Date>d(01mar2008), msize(small) xtitle("Change in misreport (monthly rate, in pp)", size(small)) ) /*
*/ (lfit DdifNM dMisrep if Date<=d(01mar2008), text(1.2 1.0 "beta=`beta'", place(e) size(small))  text(0.8 1.0 "p-val=`pval'", place(e) size(small)) lpattern(dash) color(black) legend(off) )
qui graph export "`path_FTapp'/Scatter_Dmisrep_DdiffFijo.pdf", replace
// -------------------------------------------------------------------------------------------------

}
// ------------------------------------------------------------------------------------------------------- //
// ------------------------------------------------------------------------------------------------------- //
// END OF `Figure_B4_to_B6' == 1


